package com.yihu.wlyy.util;

import org.springside.modules.security.utils.Digests;
import org.springside.modules.utils.Encodes;

import com.yihu.wlyy.entity.doctor.Doctor;
import com.yihu.wlyy.entity.IdEntity;
import com.yihu.wlyy.entity.patient.Patient;

public class EncodesUtil {
	
	public static final String HASH_ALGORITHM = "SHA-1";
	public static final int HASH_INTERATIONS = 1024;
	private static final int SALT_SIZE = 8;
	
	/**
	 * 设定安全的密码，生成随机的salt并经过1024次 sha-1 hash
	 */
	public static void entryptPassword(IdEntity entity) {
		if(entity == null){
			return ;
		}
		byte[] salt = Digests.generateSalt(SALT_SIZE);
		if(entity instanceof Doctor){
			Doctor doctor = (Doctor) entity;
			doctor.setSalt(Encodes.encodeHex(salt));
			byte[] hashPassword = Digests.sha1(doctor.getPassword().getBytes(), salt, HASH_INTERATIONS);
			doctor.setPassword(Encodes.encodeHex(hashPassword));
		}else if(entity instanceof Patient){
			Patient patient = (Patient) entity;
			patient.setSalt(Encodes.encodeHex(salt));
			byte[] hashPassword = Digests.sha1(patient.getPassword().getBytes(), salt, HASH_INTERATIONS);
			patient.setPassword(Encodes.encodeHex(hashPassword));
		}
	}
	
	/**
	 * 设定安全的密码，生成随机的salt并经过1024次 sha-1 hash
	 */
	public static String entryptPassword(byte[] salt, String password) {
		byte[] hashPassword = Digests.sha1(password.getBytes(), salt, HASH_INTERATIONS);
		return Encodes.encodeHex(hashPassword);
	}
	
	public static void main(String[] args) {
		System.out.println(entryptPassword(Encodes.decodeHex("e17354680a03a774"), "123456"));
	}

}
